package com.ctaa.login;

import androidx.appcompat.app.AppCompatActivity;

import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.Editable;
import android.text.InputType;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.alibaba.fastjson.JSONObject;
import com.common.api.RouterPath;
import com.common.pojo.app.UserInfoPojo;
import com.common.pojo.dto.Result;
import com.common.utils.Constants;
import com.common.utils.ConstantsUrl;
import com.common.utils.MD5Utils;
import com.common.utils.MethodUtils;
import com.common.utils.ValidationUtils;
import com.ctaa.MainActivity;
import com.ctaa.R;
import com.ctaa.databinding.ActivityLoginBinding;
import com.patch.AppUpdate;
import com.zhy.http.okhttp.OkHttpUtils;
import com.zhy.http.okhttp.callback.StringCallback;

import cn.pedant.SweetAlert.SweetAlertDialog;
import okhttp3.Call;

public class LoginActivity extends AppCompatActivity {

    private ActivityLoginBinding loginBinding;
    private EditText emailEditText, passwordEditText;
    private Button loginButton;
    private TextView registerTextView, forgotPasswordTextView;

    private boolean passwordVisible = false;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        loginBinding = ActivityLoginBinding.inflate(getLayoutInflater());

        setContentView(loginBinding.getRoot());

        // 初始化视图
        initViews();

        // 设置输入监听器
        setupInputListeners();

        // 设置按钮点击事件
        setupButtonListeners();

        //检查更新
        updateVsersion();
    }

    private void updateVsersion() {
        AppUpdate.appUpdate(1, this, "com.ctaa", MethodUtils.getFilesDir(), ConstantsUrl.versionUrl);
    }

    private void initViews() {

        emailEditText = loginBinding.emailEditText;

        passwordEditText = loginBinding.passwordEditText;
        loginButton = loginBinding.loginButton;
        registerTextView = loginBinding.registerTextView;
        forgotPasswordTextView = loginBinding.forgotPasswordTextView;

        // 应用动画
        animateElements();

        //设置密码眼睛点击事件
        loginBinding.togglePasswordVisibility.setOnClickListener(v -> {
            passwordVisible = !passwordVisible;
            if (passwordVisible) {
                // 显示密码
                loginBinding.passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
                loginBinding.togglePasswordVisibility.setImageResource(R.drawable.ic_eye);
            } else {
                // 隐藏密码
                loginBinding.passwordEditText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD);
                loginBinding.togglePasswordVisibility.setImageResource(R.drawable.ic_eye_closed);
            }

            // 光标定位到文本末尾
            loginBinding.passwordEditText.setSelection(loginBinding.passwordEditText.getText().length());

        });

    }

    private void animateElements() {
        // 应用标志动画
        View logoContainer = loginBinding.logoContainer;
        Animation fadeIn = AnimationUtils.loadAnimation(this, R.anim.fade_in);
        logoContainer.startAnimation(fadeIn);

        // 表单动画
        View formContainer = loginBinding.formContainer;
        Animation slideUp = AnimationUtils.loadAnimation(this, R.anim.slide_up);
        formContainer.startAnimation(slideUp);

    }

    private void setupInputListeners() {
        // 监听邮箱和密码输入，启用/禁用登录按钮
        TextWatcher textWatcher = new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {
                updateLoginButtonState();
            }

            @Override
            public void afterTextChanged(Editable s) {
            }
        };

        emailEditText.addTextChangedListener(textWatcher);
        passwordEditText.addTextChangedListener(textWatcher);
    }

    private void updateLoginButtonState() {
        String email = emailEditText.getText().toString().trim();
        String password = passwordEditText.getText().toString().trim();

        // 启用登录按钮当邮箱和密码都不为空
        loginButton.setEnabled(!email.isEmpty() && !password.isEmpty());
        loginButton.setText("登录");
        // 根据按钮状态改变背景颜色
        if (loginButton.isEnabled()) {
            loginButton.setBackgroundResource(R.drawable.button_gradient_blue);
        } else {
            loginButton.setBackgroundResource(R.drawable.button_gradient_gray);
        }
    }

    private void setupButtonListeners() {
        // 登录按钮点击事件
        loginButton.setOnClickListener(v -> {
            // 显示加载动画
            loginButton.setText("登录中...");
            loginButton.setEnabled(false);

            // 模拟登录过程
            simulateLogin();
        });

        // 注册文本点击事件
        registerTextView.setOnClickListener(v -> {
            // 跳转到注册页面
            Intent intent = new Intent(LoginActivity.this, RegisterActivity.class);
            startActivity(intent);
            // 添加过渡动画
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        });

        // 忘记密码点击事件
        forgotPasswordTextView.setOnClickListener(v -> {
            // 跳转到找回密码页面
            Intent intent = new Intent(LoginActivity.this, ForgotPasswordActivity.class);
            startActivity(intent);
            // 添加过渡动画
            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);
        });

    }

    private void simulateLogin() {


        String email = emailEditText.getText().toString();
        String password = passwordEditText.getText().toString();
        if (email == null || "".equalsIgnoreCase(email)) {
            showToast("邮箱不能为空");
            updateLoginButtonState();
            return;
        }
        if (password == null || "".equalsIgnoreCase(password)) {
            showToast("密码不能为空");
            updateLoginButtonState();
            return;
        }
        boolean validEmail = ValidationUtils.isValidEmail(email);
        if (!validEmail) {
            showToast("邮箱格式不正确");
            updateLoginButtonState();
            return;
        }

        OkHttpUtils.get().url(ConstantsUrl.loginUrl)
                .addParams("email", email)
                .addParams("password", MD5Utils.encrypt(password))
                .build()
                .execute(new StringCallback() {
                    @Override
                    public void onError(Call call, Exception e, int id) {
                        if (e instanceof java.net.SocketTimeoutException) {
                            showToast("网络连接超时，请检查网络设置");
                        } else if (e instanceof java.io.IOException) {
                            showToast("网络请求失败，请检查网络连接");
                        } else {
                            showToast("网络请求出现未知错误");
                        }
                        updateLoginButtonState();
                    }

                    @Override
                    public void onResponse(String response, int id) {
                        updateLoginButtonState();
                        Result result = null;
                        try {
                            result = JSONObject.parseObject(response, Result.class);
                        } catch (Exception e) {
                        }
                        if (result == null) {
                            result = Result.fail("登录请求返回失败");
                        }
                        if (result.getSuccess()) {
                            UserInfoPojo userInfo = JSONObject.parseObject(result.getData().toString(), UserInfoPojo.class);
                            String user = JSONObject.toJSONString(userInfo);
                            Constants.userInfo = user;
                            /**
                             * 记录账号密码，下次自动登录
                             */
                            SharedPreferences preferences = getSharedPreferences("login", MODE_PRIVATE);
                            preferences.edit().putString("userInfo", user).apply();

                            // 登录成功，跳转到主页面
                            Intent intent = new Intent(LoginActivity.this, MainActivity.class);
                            startActivity(intent);
                            finish();
                            // 添加过渡动画
                            overridePendingTransition(R.anim.slide_in_right, R.anim.slide_out_left);

                        } else {
                            showToast(result.getMessage());
                        }

                    }
                });
    }


    private void showToast(String content) {
        runOnUiThread(() -> {
            Toast.makeText(LoginActivity.this, content, Toast.LENGTH_SHORT).show();
        });
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK && event.getRepeatCount() == 0) {
            new SweetAlertDialog(this, SweetAlertDialog.WARNING_TYPE)
                    .setTitleText("提示")
                    .setContentText("是否退出系统？")
                    .setConfirmText("确定")
                    .setConfirmClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                            System.exit(0);
                        }
                    })
                    .setCancelText("取消")
                    .setCancelClickListener(new SweetAlertDialog.OnSweetClickListener() {
                        @Override
                        public void onClick(SweetAlertDialog sweetAlertDialog) {
                            sweetAlertDialog.dismiss();
                        }
                    })
                    .show();
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }
}